package com.cah.game;

import java.util.concurrent.ExecutionException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.cah.library.UserFunctions;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

public class GameCzarFragment extends GameUIFragment
{
	private int subsNeeded;
	private JSONObject submissionsInfo;
	Button submitBlackButton;
	RadioGroup submissionRadioGroup;
	String[] playerKeys;
	MainActivity main;
	
	public GameCzarFragment(String gameKey, JSONObject gameInfo)
	{
		super();
		this.gameKey = gameKey;
		this.gameInfo = gameInfo;
	}
	
	public GameCzarFragment()
	{
		super();
	}
	
	public void onSaveInstanceState(Bundle outState)
	{
		super.onSaveInstanceState(outState);
		if(submissionsInfo != null)
		{
			outState.putString("submissionsInfo", submissionsInfo.toString());
		}
	}
	
	public void onActivityCreated(Bundle savedInstanceState)
	{
		super.onActivityCreated(savedInstanceState);
			
		submitBlackButton = (Button)main.findViewById(R.id.submitBlackButton);
		submissionRadioGroup = (RadioGroup)main.findViewById(R.id.submissionRadio);
		
		submitBlackButton.setOnClickListener(new View.OnClickListener()
		{
			
			@Override
			public void onClick(View arg0)
			{
				if(submissionRadioGroup.getCheckedRadioButtonId() != -1)
				{
					String winnerId = playerKeys[submissionRadioGroup.getCheckedRadioButtonId()];
					new SubmitBlackProcess().execute(winnerId);
				}
				else
				{
					Toast.makeText(main, "Must make a selection!", Toast.LENGTH_SHORT).show();
				}
				
			}
		});
		
		
		
		try
		{
			subsNeeded = gameInfo.getInt("subsNeeded");
		} catch (JSONException e)
		{
			e.printStackTrace();
		}
		
		
		gameHeader.setText("Round " + Integer.toString(currentRound) + ": YOU are picking.");
		
		if(subsNeeded>0)
		{
			instructionTextView.setText("Still waiting for " + Integer.toString(subsNeeded));
			submitBlackButton.setEnabled(false);
		}
		else
		{
			instructionTextView.setText("Everyone has submitted!  You may now pick.");
			if(savedInstanceState == null)
			{
				new GetSubmissionsProcess().execute();
			}
			else
			{
				try
				{
					submissionsInfo = new JSONObject(savedInstanceState.getString("submissionsInfo"));
				} catch (JSONException e)
				{
					e.printStackTrace();
				}
				setSubmissions();
			}
		}
	}
	
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
	{
		return inflater.inflate(R.layout.game_czar, container, false);
	}
	
	private class GetSubmissionsProcess extends AsyncTask<Void, Void, JSONObject>
	{
		ProgressDialog pdia;
		@Override
		protected void onPreExecute()
		{
			pdia = new ProgressDialog(main);
			pdia.setMessage("Loading game...");
			pdia.show();
		}
		
		@Override
		protected JSONObject doInBackground(Void... params)
		{
			UserFunctions uf = new UserFunctions(userKey);
			return uf.fetchSubmissions(gameKey);
		}
		
		protected void onPostExecute(JSONObject json)
		{
			submissionsInfo = json;
			setSubmissions();
			pdia.dismiss();
		}
		
	}
	
	private void setSubmissions()
	{
		try
		{
			if(submissionsInfo.getInt("success")==1)
			{
				JSONArray submissions = submissionsInfo.getJSONArray("value");
				playerKeys = new String[submissions.length()];
				
				for(int i=0;i<submissions.length();i++)
				{
					JSONObject submission = submissions.getJSONObject(i);
					String playerKey = submission.getString("playerKey");
					playerKeys[i] = playerKey;
					JSONArray submittedCards = submission.getJSONArray("submission");
					
					String submissionText = "";
					int[] submittedCardIds = new int[submittedCards.length()];
					
					for(int j=0;j<submittedCards.length();j++)
					{
						submittedCardIds[j] = submittedCards.getInt(j);
					}
					
					GetWhiteCardTextProcess whiteProcess = new GetWhiteCardTextProcess();
					whiteProcess.execute(submittedCardIds);
					SparseArray<String> whiteCardIdMap = whiteProcess.get();
					
					for(int j=0;j<submittedCardIds.length;j++)
					{
						if(j>0)
						{
							submissionText += ", ";
						}
						submissionText += whiteCardIdMap.get(submittedCardIds[j]);
					}
					
					RadioButton rb = new RadioButton(main);
					rb.setText(submissionText);
					rb.setTextColor(getResources().getColor(R.color.black));
					rb.setId(i);
					
					
					submissionRadioGroup.addView(rb);
				}
			}
			else
			{
				Toast.makeText(main, "ruh roh.", Toast.LENGTH_SHORT).show();
			}
		} catch (JSONException e)
		{
			e.printStackTrace();
		} catch (InterruptedException e)
		{
			e.printStackTrace();
		} catch (ExecutionException e)
		{
			e.printStackTrace();
		}
	}
	
	private class SubmitBlackProcess extends AsyncTask<String, Void, JSONObject>
	{
		ProgressDialog pdia;
		@Override
		protected void onPreExecute()
		{
			pdia = new ProgressDialog(main);
			pdia.setMessage("Submitting your choice...");
			pdia.show();
		}
		
		@Override
		protected JSONObject doInBackground(String... params)
		{
			String winnerId = params[0];
			UserFunctions uf = new UserFunctions(userKey);
			return uf.submitBlack(winnerId, gameKey);
		}
		
		protected void onPostExecute(JSONObject json)
		{
			try
			{
				if(json.getInt("success")==1)
				{
					main.startGameFragment(gameKey, 1);
				}
				else
				{
					Toast.makeText(main, "Something went wrong!", Toast.LENGTH_SHORT).show();
				}
			} catch (JSONException e)
			{
				e.printStackTrace();
			}
			
			pdia.dismiss();
		}
		
	}
}
